import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action } from '@ngrx/store';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import { AuthService } from '../services/auth.service';
import { AuthActionTypes, LoginSuccessAction, LoginFailAction, RegisterSuccessAction, RegisterFailAction } from '../actions/auth.action';
import { User } from '../domain/index';
import { Router } from '@angular/router';
@Injectable()
export class AuthEffects {
    @Effect()
    login$: Observable<Action> = this.actions$
        .ofType(AuthActionTypes.LOGIN)
        .map(toPayload)
        .switchMap(({ email, password }) => this.service$.login(email, password)
            .map(auth => new LoginSuccessAction(auth))
            .catch(err => Observable.of(new LoginFailAction(JSON.stringify(err))))
        );
    @Effect()
    register$: Observable<Action> = this.actions$
        .ofType(AuthActionTypes.REGISTER)
        .map(toPayload)
        .switchMap((user: User) => this.service$.regisiter(user)
            .map(auth => new RegisterSuccessAction(auth))
            .catch(err => Observable.of(new RegisterFailAction(JSON.stringify(err))))
        );
    @Effect()
    logout$: Observable<Action> = this.actions$
        .ofType(AuthActionTypes.LOGOUT)
        .map(_ => {
            this.router.navigate(['/']);
            return null;
        });

    @Effect({ dispatch: false })
    loginAndNaviagte$: Observable<Action> = this.actions$
        .ofType(AuthActionTypes.LOGIN_SUCCESS)
        .map(_ => {
            this.router.navigate(['/project']);
            return null;
        });

    @Effect({ dispatch: false })
    registerAndNaviagte$: Observable<Action> = this.actions$
        .ofType(AuthActionTypes.REGISTER_SUCCESS)
        .map(_ => {
            this.router.navigate(['/project']);
            return null;
        });
    constructor(
        private actions$: Actions,
        private service$: AuthService,
        private router: Router
    ) { }
}
